<template>
    <div>
        <div class="tagUsers">
            <Tag
                type="dot"
                v-for="(item, index) in selectUserList"
                v-bind:key="index"
                closable
                color="primary"
                :name="item.user_id"
                @on-close="close"
                >{{ item.user_name ? item.user_name : item.user_id }}</Tag
            >
        </div>
        <div class="searchContent">
            <el-select v-model="optionValue" style="width: 100px" size="mini">
                <el-option v-for="item in options" :value="item.value" :key="item.value" :label="item.label"></el-option>
            </el-select>
            <el-input
                v-model="userName"
                placeholder="请输入用户名称"
                size="mini"
                style="width: 150px; margin-right: 10px; margin-left: 10px"
            ></el-input>
            <custom-button type="search" style="margin-right: 10px" @searchClick="searchClick"></custom-button>
            <custom-button type="reset" style="margin-right: 10px" @resetClick="resetClick"></custom-button>
            <custom-button type="save" @saveClick="saveClick"></custom-button>
        </div>
        <div>
            <table-index
                ref="curTable"
                :dataSource="dataSource"
                :tableColumns="tableColumns"
                :btnList="[]"
                :pageSize="pageSize"
                :pageCount="pageCount"
                :pageNo="pageNo"
                @pageChange="pageChange"
                @handleSelectionChange="handleSelectionChange"
                :height="secondTableHeight"
            ></table-index>
        </div>
    </div>
</template>

<script>
import customDialog from '@/components/customComponents/customDialog'
import customButton from '@/components/customComponents/customForm/customButton'
import formIndex from '@/components/customComponents/customForm/formIndex'
import tableIndex from '@/components/customComponents/customeTable/iviewTable/singleViewTable'
import {AjaxCommon} from '@/libs/apiCommon'
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'
export default {
    props: ['userList'],
    components: {
        customButton,
        tableIndex,
        customDialog,
        formIndex
    },
    data() {
        return {
            // 初始化传过来的userList，本身的集合值
            selectUserList: [],
            // 每页勾选的值
            pageUserList: [],
            value: [],
            optionValue: 'name',
            options: [
                {
                    value: 'name',
                    label: '登录名'
                },
                {
                    value: 'realname',
                    label: '真实姓名'
                }
            ],
            orgInfo: {},
            secondTableHeight: 350,
            selectOrgList: [],
            userName: null,
            curTitle: '用户管理',
            // table 相关参数  begin
            dataSource: [],
            tableColumns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    key: 'user_id',
                    title: '登录名'
                },
                {
                    key: 'user_name',
                    title: '真实姓名'
                },
                {
                    key: 'user_sex',
                    title: '性别',
                    slot: 'user_sex'
                },
                {
                    key: 'user_m_tel',
                    title: '手机号码'
                },

                {
                    key: 'user_email',
                    title: '用户邮箱'
                },
                {
                    key: 'user_address',
                    title: '住址'
                },

                {
                    key: 'is_enable',
                    title: '是否启用',
                    slot: 'is_enable'
                }
            ],
            pageSize: 20,
            pageCount: 100,
            pageNo: 1
            // table 相关参数  end
        }
    },
    created() {
        this.selectUserList = this.userList
    },
    methods: {
        close(event, name) {
            const index = this.selectUserList.findIndex((t) => t.user_id == name)
            this.selectUserList.splice(index, 1)
            this.$refs.curTable.setSingleCheckboxToggle(index)
        },
        getOrgInfo(item) {
            this.orgInfo = item
            this.curTitle = item.fullName
            this.searchClick()
        },
        getHeight() {
            this.secondTableHeight = 350
        },
        customClick(isTrue) {
            this.useOrg(isTrue)
        },
        handleSelectionChange(d) {
            Utility.debounce(() => {
                // 不同页面所有勾选中的数据
                let selectUserList = JSON.parse(JSON.stringify(this.selectUserList))
                // 当前页原始数据
                let oldData = JSON.parse(JSON.stringify(this.pageUserList.filter((t) => t.page == this.pageNo)))

                // 确认新增的
                let addData = []
                // 确认删除的
                let deleteData = []
                let deleteData1 = []

                // 返回为空的情况，说明全删除了
                if (d.length == 0) {
                    deleteData = JSON.parse(JSON.stringify(oldData))
                    deleteData1 = JSON.parse(JSON.stringify(oldData))
                } else {
                    // 判断新增的
                    d.forEach((t) => {
                        if (oldData.find((o) => o.user_id == t.user_id) == null) {
                            addData.push(t)
                        }
                    })
                    // 判断删除的情况
                    oldData.forEach((t) => {
                        if (d.find((o) => o.user_id == t.user_id) == null) {
                            deleteData.push(JSON.parse(JSON.stringify(t)))
                            deleteData1.push(JSON.parse(JSON.stringify(t)))
                        }
                    })
                }

                if (addData.length == 0 && deleteData.length == 0) {
                    // 说明没有变化
                    return
                }

                // 改变当前页
                addData.forEach((t) => {
                    oldData.push({
                        page: this.pageNo,
                        user_id: t.user_id
                    })
                })

                for (let odIndex = oldData.length - 1; odIndex >= 0; odIndex--) {
                    const ddIndex = deleteData.findIndex((dd) => dd.user_id == oldData[odIndex].user_id)
                    if (ddIndex !== -1) {
                        oldData.splice(odIndex, 1)
                    }
                }

                this.pageUserList = oldData

                // 改变所有值
                addData.forEach((t) => {
                    selectUserList.push(t)
                })
                for (let osIndex = selectUserList.length - 1; osIndex >= 0; osIndex--) {
                    const ddIndex = deleteData1.findIndex((dd) => dd.user_id == selectUserList[osIndex].user_id)
                    if (ddIndex !== -1) {
                        selectUserList.splice(osIndex, 1)
                    }
                }

                this.selectUserList = selectUserList
            })
        },
        formInputChange(e) {
            if (e.filedName == 'idCard') {
            }
        },
        searchClick() {
            this.pageNo = 1
            this.initPage()
        },
        resetClick() {
            this.userName = null
            this.searchClick()
        },
        saveClick() {
            if (this.selectUserList.length == 0) {
                PopupCommon.notify('info', '请勾选用户')
                return
            }
            this.$emit('getData', this.selectUserList)
        },
        // 分页点击事件
        pageChange(p) {
            this.pageNo = p
            this.initPage()
        },
        // 初始化事件
        initPage() {
            let self = this
            let params = `/api/User/GetUsersByOrg?PageSize=${this.pageSize}&PageIndex=${this.pageNo}`
            if (this.userName) {
                params += `&value=${this.userName}&where=${this.optionValue}`
            }
            AjaxCommon(params, 'get', null).then((res) => {
                if (res?.data?.Code == 200) {
                    const data = res?.data.Message
                    self.dataSource = data?.rows
                    setTimeout(() => {
                        // checkbox自动选中
                        const roleIds = self.selectUserList?.map((b) => b.user_id)
                        // user_name
                        self.dataSource?.forEach((t, i) => {
                            if (roleIds.includes(t.user_id)) {
                                self.pageUserList.push({
                                    page: self.pageNo,
                                    user_id: t.user_id
                                })
                                self.$refs.curTable.setSingleCheckboxToggle(i)
                            }
                        })
                    }, 50)
                    self.pageCount = parseInt(data?.total)
                } else {
                    PopupCommon.notify('error', res?.data?.msg)
                }
            })
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getHeight()
            this.initPage()
        })

        /*窗口自适应，关键代码*/
        window.onresize = () => {
            this.getHeight()
        }
    }
}
</script>

<style lang="scss" scoped>
.tagUsers {
    max-height: 120px;
    min-height: 40px;
    width: 100%;
    overflow: auto;
    margin-bottom: 10px;
}
.searchContent {
    display: flex;
    width: 100%;
    align-items: center;
    margin-bottom: 10px;
    justify-content: flex-end;
}
</style>
